﻿using System.Collections.Generic;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Game.Contract;
using ZyGames.Framework.Common.Serialization;
using ZyGames.Framework.Game.Cache;
using ZyGames.Framework.Game.Lang;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.DZPocker.Script;
using ZyGames.DZPocker.Tools;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 10045请求离开房间
	/// </summary>
	public class Action10045 : BaseAction
	{
		private int tableId;
		private int userId;
		private bool result = false;
		public Action10045(HttpGet actionGetter)
			: base((short)ActionType.DZApplyLeaveRoom, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetInt("TableID", ref tableId) &&
				httpGet.GetInt("UserID", ref userId))
			{
				return true;
			}
			return false;
		}

		public override bool TakeAction()
		{
			var _currentGameUser = GameTable.Current.GetUser(userId);
			if (_currentGameUser == null)
			{
				ErrorCode = Language.Instance.ErrorCode;
				return false;
			}
			var _currentTable = GameRoom.Current.GetTableData(tableId);
			if (_currentTable == null)
			{
				Tool.WriteErrorLine("消息10045获得房间不存在");
				return false;
			}
			int posId = -1;
			if(_currentGameUser.Property.PositionId.TryGetValue(tableId, out posId))
			{
				if(posId > 0)
				{
					if (posId < 1 || posId > 9)
					{
						Tool.WriteErrorLine("消息10045座位号不是1-9不合法");
						return false;
					}
					else
					{
						//判断是否正在玩
						var pos = _currentTable.Positions[posId - 1];
						if (pos == null)
						{
							Tool.WriteErrorLine("10045不存在这个座位");
							return false;
						}
						if (_currentTable.State == TableState.Countdown || pos.PlayState == PositionPlayState.Add || pos.PlayState == PositionPlayState.AllIn || pos.PlayState == PositionPlayState.Follow || pos.PlayState == PositionPlayState.Look)
						{
							Tool.WriteLine("10045玩家正在游戏中，离开房间失败");
							return false;
						}
						//坐下状态的话就先站起
						GameTable.Current.LeaveTable(_currentTable, _currentGameUser, pos);
					}
				}
			}
			result = true;
			return true;
		}

		public override void BuildPacket()
		{
			this.PushIntoStack(this.tableId);
			this.PushIntoStack(this.result);
			this.PushIntoStack(this.userId);
		}
	}
}
